package com.yupi.moonBI.mq;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DeliverCallback;

import java.util.HashMap;
import java.util.Map;

/**
 * 延迟队列消费者
 */
public class DelayConsumer {
    private static final String EXCHANGE_NAME = "order_exchange";
    private static final String DEL_EXCHANGE_NAME = "order_exchange_dlx";

    public static void main(String[] argv) throws Exception {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("192.168.88.130");
        factory.setPort(5672);
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();

        Map<String,Object> args = new HashMap<>();
        args.put("x-dead-letter-exchange",DEL_EXCHANGE_NAME);
        args.put("x-dead-letter-routing-key", "orderdlx");
        args.put("x-message-ttl",10000);

        //创建死信队列
        String queueName2 = "order_queue_dlx";
        //Map<String,Object> arg01 = new HashMap<>();
        //arg01.put("x-dead-letter-exchange",DEL_EXCHANGE_NAME);
        //arg01.put("x-dead-letter-routing-key", "orderdlx");
        channel.queueDeclare(queueName2, true, false, false, null);
        channel.queueBind(queueName2, DEL_EXCHANGE_NAME, "orderdlx");


        //创建正常队列
        String queueName = "order_queue";
        channel.queueDeclare(queueName, true, false, false, args);
        channel.queueBind(queueName, EXCHANGE_NAME, "order");


        System.out.println(" [*] Waiting for messages. To exit press CTRL+C");

        DeliverCallback deliverCallback1 = (consumerTag, delivery) -> {
            String message = new String(delivery.getBody(), "UTF-8");
            //拒绝消息
            channel.basicNack(delivery.getEnvelope().getDeliveryTag(), false,false);
            System.out.println(" [order_queue] Received '" + delivery.getEnvelope().getRoutingKey()+"："+ message + "'");
        };
        DeliverCallback deliverCallback2 = (consumerTag, delivery) -> {
            String message = new String(delivery.getBody(), "UTF-8");
            //拒绝消息
            channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
            System.out.println(" [order_queue_dlx] Received '" + delivery.getEnvelope().getRoutingKey()+"："+ message + "'");
        };
        //消息队列监听
        channel.basicConsume(queueName, false, deliverCallback1, consumerTag -> {
        });
        channel.basicConsume(queueName2, false, deliverCallback2, consumerTag -> {
        });
    }
}
